package com.android.dialer.extendboard;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.content.ContentResolver;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.google.gson.Gson;
import com.android.dialer.extendboard.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SpeedDialActivity extends AppCompatActivity {

    private final List<SpeedDialItem> items = new ArrayList<>();
    private int currentEditIndex = -1;
    private ContentResolver contentResolver;
    private final String TAG = "SpeedDialActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speed_dial);

        // Initialize ContentResolver
        contentResolver = getContentResolver();

        // Set up Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        // Set up RecyclerView
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Load data from SharedPreferences
        loadDataFromSharedPreferences(recyclerView);
    }

    private void loadDataFromSharedPreferences(RecyclerView recyclerView) {
        Cursor cursor = contentResolver.query(PhonesContentProvider.CONTENT_URI, null, null, null, null);
        items.clear();
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    do {
                        String key = cursor.getString(cursor.getColumnIndexOrThrow(PhonesContentProvider.COLUMN_KEY));
                        String value = cursor.getString(cursor.getColumnIndexOrThrow(PhonesContentProvider.COLUMN_VALUE));

                        Log.d(TAG, "loadDataFromSharedPreferences: key: " + key + ", value: " + value);
                        try {
                            SpeedDialItem item = new Gson().fromJson(value, SpeedDialItem.class);
                            if (item != null) {
                                items.add(item);
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "loadDataFromSharedPreferences: error parsing json", e);
                        }
                    } while (cursor.moveToNext());
                }
            } finally {
                cursor.close();
            }
        } else {
            Log.e(TAG, "loadDataFromSharedPreferences: query failed");
            Toast.makeText(this, "Failed to read data.", Toast.LENGTH_SHORT).show();
        }

        recyclerView.setAdapter(new SpeedDialAdapter(items, this, new SpeedDialAdapter.OnItemClickListener() {
            @Override
            public void onEditClick(SpeedDialItem item) {
                // Open PickContact activity and wait for result
                Intent intent = new Intent(SpeedDialActivity.this, PickContact.class);
                intent.putExtra("key", item.getId());
                currentEditIndex = items.indexOf(item);
                startActivityForResult(intent, 1);
            }

            @Override
            public void onDeleteClick(SpeedDialItem item) {
                // Handle delete click
                item.setActive(false);
                item.setAvatar("");
                item.setName("");
                item.setNumber("");

                contentResolver.delete(PhonesContentProvider.CONTENT_URI, null, new String[]{String.valueOf(item.getId())});
                // Update the adapter, don't remove the item
                Objects.requireNonNull(recyclerView.getAdapter()).notifyItemChanged(items.indexOf(item));
            }
        }));
    }

    // Get result from PickContact
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult: " + requestCode + " " + resultCode);
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            SpeedDialItem item = bundle.getParcelable("item");
            Log.d(TAG, "onActivityResult: " + item.toString());

            // Notify adapter about the change
            ContentValues values = new ContentValues();
            values.put(PhonesContentProvider.COLUMN_KEY, String.valueOf(item.getId()));
            values.put(PhonesContentProvider.COLUMN_VALUE, new Gson().toJson(item));
            int updatedRows = contentResolver.update(PhonesContentProvider.CONTENT_URI, values, null, null);

            Log.d(TAG, "onActivityResult: " + updatedRows);

            items.set(currentEditIndex, item);
            RecyclerView recyclerView = findViewById(R.id.recyclerView);
            Objects.requireNonNull(recyclerView.getAdapter()).notifyItemChanged(currentEditIndex);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}